﻿using System;
using System.IO;
using System.Runtime.InteropServices;

namespace Puerts
{
    public class CopyDep
    {
        static bool inited = false;
        public static void Init()
        {
            Console.WriteLine("CopyDep Init");
            if (inited)
                return;

            inited = true;

            bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            bool isMac = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
            bool isLinux = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
            Console.WriteLine("isWindows "+isWindows);
            Console.WriteLine("isMac " + isMac);
            Console.WriteLine("isLinux " + isLinux);
            Console.WriteLine("RuntimeInformation.OSArchitecture " + RuntimeInformation.OSArchitecture);
            Console.WriteLine("curdir=" + AppDomain.CurrentDomain.BaseDirectory);

            var dir = AppDomain.CurrentDomain.BaseDirectory;
            try
            {
                File.Delete(Path.Combine(dir, "libpuerts.dylib"));
                File.Delete(Path.Combine(dir, "puerts.dll"));
                File.Delete(Path.Combine(dir, "puerts.bundle"));
                File.Delete(Path.Combine(dir, "libpuerts.so"));
            }
            catch
            {

            }
            Console.WriteLine("delete file");

            if (Environment.Is64BitProcess == false)
            {
                Console.WriteLine("only support 64");

                throw new Exception("only support 64bit");
            }
            else if (RuntimeInformation.OSArchitecture == Architecture.Arm64 && isMac)
            {

                File.Copy(Path.Combine(dir, "macOS/arm64/libpuerts.dylib"), Path.Combine(dir, "libpuerts.dylib"));
            }
            else if (RuntimeInformation.OSArchitecture == Architecture.X64 && isMac)
            {
                File.Copy(Path.Combine(dir, "macOS/x86_64/puerts.bundle"), Path.Combine(dir, "puerts.bundle"));

            }
            else if (RuntimeInformation.OSArchitecture == Architecture.X64 && isWindows)
            {
                Console.WriteLine("Windows + X64");
                File.Copy(Path.Combine(dir, "x86_64/puerts.dll"), Path.Combine(dir, "puerts.dll"));
            }
            else if (RuntimeInformation.OSArchitecture == Architecture.Arm64 && isWindows)
            {
                File.Copy(Path.Combine(dir, "x86_64/puerts.dll"), Path.Combine(dir, "puerts.dll"));
            }
            else if (RuntimeInformation.OSArchitecture == Architecture.X64 && isLinux)
            {
                File.Copy(Path.Combine(dir, "x86_64/libpuerts.so"), Path.Combine(dir, "libpuerts.so"));
            }
        }
    }
}
